<template>
    <Header title='JD商城' class="headerColor">
        <template #left>
            <van-icon name="arrow-left" @click="tobackFn" />
        </template>
    </Header>
    <div class="Form_Box">
        <van-form @submit="submitHandler">
            <van-field style="margin:20px auto;" v-model="username" name="用户名" label="用户名" placeholder="用户名"
                :rules="[{ required: true, message: '请填写用户名', pattern: /\w{6,12}/ }]" />
            <van-field style="margin:20px auto;" v-model="password" type="password" name="密码" label="密码"
                placeholder="密码" :rules="[{ required: true, message: '请填写密码' }]" />
            <div style="margin:20px 16px;">
                <van-button round block native-type="submit"
                    color="linear-gradient(to right, #ff6034, #ee0a24)">提交</van-button>
            </div>
        </van-form>
        <p>还没有密码？<router-link to="/registration">注册</router-link></p>

    </div>

</template>

<script setup lang="ts">
import { Toast } from 'vant';
import { ref } from 'vue'
import { useRouter, type Router } from 'vue-router'
import { loginApi } from '@/api/user'
import router from '@/router';
const username = ref<string>('')
const password = ref<string>('')

//返回上一级
const tobackFn = () => {
    router.go(-1)
}

const $router: Router = useRouter()
const submitHandler = async () => {
    const res = await loginApi(password.value)
    console.log('登录',username.value ,  res);
    if (((res as unknown) as { code: string }).code == '200') {
        Toast({
            message: '登录成功',
            icon: 'like-o',
        });
        //成功之后存储一下账号信息
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('user_id', res.data.userid)
        // localStorage.setItem('user_name', username.value)

        //跳转到首页
        setTimeout(() => {
            $router.push({
                path: '/home'
            })
        }, 2000)
        return
    }
    // 代码执行到这里, 说明手机号不行
    Toast({
        message: '登录失败',
        icon: 'phone-circle-o',
    })
}





</script>
<style scoped lang="scss">
.Form_Box {
    width: 90%;
    padding: 15px;
    box-sizing: border-box;
    border: 1px solid black;
    border-radius: 10px;

    margin: 250px auto;
}
</style>